﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Circle.Domain.Entity;
using Circle.Domain.Interface.Service;
using Circle.Domain.Model;
using Circle.Domain.Interface.Repository;
using System.Data.Entity;

namespace Circle.Service
{
    public class TopicService : BaseOwnerCrudService<ContentTopic>, ITopicService
    {
        private readonly ICommentService _commentService;
        private readonly IBannedWordService _bannedWordService;
        private readonly ISettingService _settingService;
        private readonly Setting _defaultSetting;


        static TopicService()
        {

            PermissionNameDictionary.Add(EntityPermission.Read, PermissionConstants.Topic_Read);
            PermissionNameDictionary.Add(EntityPermission.Add, PermissionConstants.Topic_Add);
            PermissionNameDictionary.Add(EntityPermission.Update, PermissionConstants.Topic_Update);
            PermissionNameDictionary.Add(EntityPermission.Delete, PermissionConstants.Topic_Delete);
            PermissionNameDictionary.Add(EntityPermission.Vote, PermissionConstants.Topic_Vote);

            PermissionNameDictionary.Add(EntityPermission.UploadDocumentRead, PermissionConstants.Topic_Upload_Document_Read);
            PermissionNameDictionary.Add(EntityPermission.UploadDocument, PermissionConstants.Topic_Upload_Document);
            PermissionNameDictionary.Add(EntityPermission.UploadImage, PermissionConstants.Topic_Upload_Image);

        }

        public TopicService(ICommentService commentService, IBannedWordService bannedWordService, SettingService settingService)
        {
            _commentService = commentService;
            _bannedWordService = bannedWordService;
            _settingService = settingService;

            _defaultSetting = _settingService.GetDefaultSetting();
        }

        public override IQueryable<ContentTopic> All
        {
            get
            {
                return base.All.Include(x => x.FirstComment);
            }
        }

        public override ContentTopic Create()
        {
            var topic = base.Create();
            topic.With(x => {
                x.IsLocked = false;
                x.IsVisible = true;
                x.IsSticky = false;
                x.Title = string.Empty;
                //x.Content = string.Empty;
            });

            var comment = _commentService.Create();
            topic.FirstComment = comment;
           
            return topic;
        }


        protected override void OnSaving(ContentTopic item, bool checkPermission)
        {
            item.LastUpdateTime = DateTime.UtcNow;
            item.OriginalTitle = item.Title;

            char replaceHolder = _defaultSetting.BannedWordReplaceHolder[0];
            item.Title = _bannedWordService.ReplaceBannedWord(item.OriginalTitle, replaceHolder);
            item.OriginalSubTitle = item.SubTitle;
            item.SubTitle = _bannedWordService.ReplaceBannedWord(item.OriginalSubTitle, replaceHolder);
        }

        protected override OperationStatus Add(ContentTopic item)
        {
            try
            {
                item.CreateTime = DateTime.UtcNow;
                item.UserId = Security.CurrentUser.UserId;

                var firstComment = item.FirstComment;
                item.LastComment = null;
                item.FirstComment = null;

                //Save Topic
                using (var worker = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        var topicSaveStatus = AddMark(item);
                        if (topicSaveStatus == OperationStatus.Success)
                        {
                            worker.Commit();
                        }
                        else
                        {
                            throw new Exception("Topic Save Error");
                        }
                    }
                    catch 
                    {
                        item.ResetId();
                        throw new Exception("Topic Save Error");
                    }
                }

                //Save Post
                item.FirstComment = firstComment;
                firstComment.TopicId = item.Id;
                var commentSaveStatus = _commentService.Save(firstComment);

                if (commentSaveStatus != OperationStatus.Success)
                {
                    throw new Exception("Post Save Error");
                }

                return  OperationStatus.Success;

            }
            catch
            {
                if (!item.IsNew())
                {
                    Delete(item);
                }
                if (item.FirstComment != null && !item.FirstComment.IsNew())
                {
                    _commentService.Delete(item.FirstComment);
                }
                return OperationStatus.GenericError;
            }

        }


        //public override bool CheckItemApproved(EntityPermission permission, ContentTopic item)
        //{
        //    if (IsCurrentAdminUser()) return true;
            

        //    if (item!= null && item.IsLocked) return false;

        //    if ((permission == EntityPermission.Update || permission == EntityPermission.Delete) &&
        //         (Security.CurrentUser.UserId != item.UserId))
        //    {
        //        return false;
        //    }

        //    return true;
        //}

        public override bool HasPermission(EntityPermission permission,  ContentTopic item = null, Guid? threadId = null)
        {
            return true;
        }
        
    }
}
